package cn.gzmli.dtt.common.controll;

import cn.gzmli.dtt.common.annotation.Comment;
import cn.gzmli.dtt.common.entity.FileUpload;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.entity.Result;
import cn.gzmli.dtt.common.service.FileUploadSerivce;
import cn.gzmli.dtt.common.utils.BaseUtil;
import cn.gzmli.dtt.common.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传Controller
 *
 * @author Pyj
 * @date 20190731
 */
@RestController
@RequestMapping("/fileUpload")
public class FileUploadController {

    @Autowired
    private FileUploadSerivce fileUploadSerivce;

    @RequestMapping("/list")
    @ResponseBody
    @Comment("获取文件列表")
    public Result list(HttpServletRequest request, PageInfo pageInfo) throws Exception {

        List list = fileUploadSerivce.getFilesList(request, pageInfo);

        return new Result(Constant.SUCCESS, "获取文件列表信息成功", list, pageInfo);
    }

    @RequestMapping("/upload")
    @Comment("文件上传")
    public Result upload(HttpServletRequest request, MultipartFile file, Boolean isScale) throws Exception {
        return fileUploadSerivce.upload(request, file, isScale);
    }

    @RequestMapping("/showFile")
    @Comment("文件查看")
    public String showFile(HttpServletRequest request, HttpServletResponse response, Integer fileId,String url, String scalePath) throws Exception {
        FileUpload fileUpload = fileUploadSerivce.getFileUpload(fileId,url,scalePath);

        if (fileUpload!=null && BaseUtil.isNotEmpty(fileUpload.getId())) {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            // 读取文件流信息
            File file = new File(fileUpload.getPath());
            if (file.exists()) {
                try {
                    // 读取文件流信息
                    fis = new FileInputStream(file);
                    byte[] bytes = new byte[fis.available()];

                    // 解决文件下载文件名称中文乱码问题
                    String fileName = fileUpload.getName();
                    String header = request.getHeader("User-Agent").toUpperCase();
                    if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                        fileName = URLEncoder.encode(fileName, "UTF-8");
                        fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
                    } else {
                        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    }
                    // 判断是否图片格式,如是则直接在线打开
                    if(".jpeg".equalsIgnoreCase(fileUpload.getType())
                        || ".jpg".equalsIgnoreCase(fileUpload.getType())
                        || ".png".equalsIgnoreCase(fileUpload.getType())
                        || ".gif".equalsIgnoreCase(fileUpload.getType())) {
                        // 设置文件名及返回头格式 "image/png"
                        response.setContentType("image/"+fileUpload.getType().substring(1,fileUpload.getType().length()));
                        response.addHeader("Content-Disposition", "inline;fileName=" + fileName );
                    } else  {
                        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName );
                    }
                    response.setCharacterEncoding("UTF-8");
                    //文件流回写解析
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(bytes);
                    while (i != -1) {
                        os.write(bytes, 0, i);
                        i = bis.read(bytes);
                    }
                    return "显示成功！";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                return "读取不到文件流信息！";
            }
        } else {
            return "数据库找不到文件！";
        }
        return "显示失败！";
    }

    @RequestMapping("/downloadFile")
    @Comment("文件下载")
    public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, Integer fileId,String url, String scalePath) throws Exception{
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        FileUpload fileUpload = fileUploadSerivce.getFileUpload(fileId,url,scalePath);

        if (fileUpload != null) {
            File file = new File(fileUpload.getPath());
            if (file.exists()) {
                try {
                    // 读取文件流信息
                    in=new FileInputStream(new File(fileUpload.getPath()));

                    byte[] bytes = new byte[in.available()];

                    //处理IE下载文件的中文名称乱码的问题
                    String fileName = fileUpload.getName();
                    String header = request.getHeader("User-Agent").toUpperCase();
                    if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                        fileName = URLEncoder.encode(fileName, "UTF-8");
                        fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
                    } else {
                        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    }

                    in.read(bytes);
                    // 附件下载
                    headers.add("ContentType", MediaType.APPLICATION_OCTET_STREAM_VALUE);
                    headers.add("Content-Disposition", "attachment;fileName="+fileName);

                    entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(in!=null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                entity = new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.NO_CONTENT);
            }
        } else {
            entity = new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.NOT_FOUND);
        }
        return entity;
    }

    @RequestMapping("/deleteFile")
    @Comment("文件删除")
    public Result deleteFile(HttpServletRequest request, HttpServletResponse response, Integer fileId,String url, String scalePath) throws Exception {
        boolean result = fileUploadSerivce.deleteFile(request,fileId,url,scalePath);
        if(result){
            return new Result(Constant.SUCCESS, "刪除文件成功");
        }else {
            return new Result(Constant.FAIL, "刪除文件失败");
        }
    }
}
